//
//  CZStatusViewModel.swift
//  weibo
//
//  Created by Apple on 16/3/16.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
//  封装statusmodel的viewmodel
class CZStatusViewModel: NSObject {
    var status: CZStatus?
    
    //  会员等级图片
    var mbrankImage: UIImage?
    //  认证等级图片
    var verifiedLevelImage: UIImage?
    
    //  计算转发数显示的文本
    var retweetCountString: String {
        //  status?.reposts_count ?? 0
        return getCountString(11000, defaultTitle: "转发")
    }
    //  计算评论数显示的文本
    var commentCountString: String {
        return getCountString(status?.comments_count ?? 0, defaultTitle: "评论")
    }
    //  计算表态数显示的问题
    var unLikeCountString: String {
        return getCountString(status?.attitudes_count ?? 0, defaultTitle: "赞")
    }
    //  转发微博内容
    var retweetContent: String?
    
    var sourceContent: String?
    
    //  时间字符串格式化
    var timeContent: String? {
        
        //  代码已经抽取到NSDate+Extension
//        if let dt = status?.created_at {
//            
//            let date = NSDate.sinaDate(dt)
//            
//            guard let createDate = date else {
//                return nil
//            }
//            
//            return createDate.sinaDateString()
//            
//        }
//        
//        return nil
        
        //  这样写也没有错，因为只有用户登录了才进去读取数据所以用户数据和create_at一定存在
        let date = NSDate.sinaDate(status!.created_at!)
        guard let createDate = date else {
            return nil
        }
        return createDate.sinaDateString()

        
    }
    //  原始微博富文本
    var originalAttributeStr: NSMutableAttributedString?
    //  转发微博富文本
    var retweetAttributeStr: NSMutableAttributedString?
    
    //  原始微博匹配类型的结果
    var originalMatchResults: [CZMatchResult]?
    //  转发微博匹配类型的结果
    var retweetMatchResults: [CZMatchResult]?
    private func getCountString(count: Int, defaultTitle: String) -> String {
       
        if count > 0 {
            if count < 10000 {
                return "\(count)"
            } else {
                let result = CGFloat(count / 1000) / 10
                var resultString = "\(result)万"
                if resultString.containsString(".0") {
                    resultString = resultString.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultString
            }
        } else {
            return defaultTitle
        }
        
    
    }
    
    //  在首页使用这个viewmodel初始化对象
    init(status: CZStatus) {
        super.init()
        self.status = status // 注意这句代码在这里执行不会调用status的didset方法，如果想要调用可以封装一个函数把赋值操作放到函数里面
        //  处理会员
        handleMBrankImage(self.status?.user?.mbrank ?? 0)
        handleVerifiedLevelImage(self.status?.user?.verified_level ?? 0)
        //  处理转发微博内容
        handleRetWeetContent()
        //  处理来源字符串
        handleSourceContent()
        //  处理原始微博的文本，改成NSMutableAttributeString
        let result = handleStatusToAttributeString(status.text)
        originalAttributeStr = result.attr
        originalMatchResults = result.matchResults
    }
    
    // MARK:    处理逻辑
    //  根据内容生成富文本对象
    private func handleStatusToAttributeString(statusText: String?) -> (attr: NSMutableAttributedString?, matchResults: [CZMatchResult]?) {
        
        guard let statusContent = statusText else {
            return (nil,nil)
        }
        print(statusText)
        let attributedStr = NSMutableAttributedString(string: statusContent)
        //  匹配文本中是否包含表情
        /*
            usingBlock 参数
                1. 匹配的个数
                2. 匹配的结果
                3. 匹配的范围
                4. 是否停止，如果true就停止了
        */
        //  定义匹配结果数组
        var matchResponses: [CZMatchResult] = [CZMatchResult]()
        //  根据指定的正则匹配结果
        (statusContent as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, result, resultRange, _) -> Void in
            //  获取指针对应的内容,直接强转也没事
           // print(result.memory!)
            
            let matchresponse = CZMatchResult(string: result.memory! as String, range: resultRange.memory)
            
            matchResponses.append(matchresponse)
            
        }
        //  以什么分割匹配
//        (statusContent as NSString).enumerateStringsSeparatedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, result, resultRange, _) -> Void in
//            print(result.memory)
//        }
        //  保存匹配结果从后往前替换
        for matchResponse in matchResponses.reverse() {
            //  根据匹配的表情字符串，查找对应的表情模型
            if let emoticon = CZEmoticonTools.shareEmoticonTools.emoticonWithEmoticonStr(matchResponse.string) {
                //  创建CZTextAttachment对象
                let attachment = CZTextAttachment()
                //  字体大小是首页定义的字体大小
                let emoticonAttributeStr = attachment.attributedStringWithEmoticon(emoticon, font: UIFont.systemFontOfSize(contentLabelFontSize))
                //  替换生成的对象，在这里替换会有问题，多个表情出现数组替换越界，考虑使用倒着遍历替换
                attributedStr.replaceCharactersInRange(matchResponse.range, withAttributedString: emoticonAttributeStr)
            }
        }
        
        //  这句话必须要加了，因为在设置给label身上的textview的富文本的时候不加font大小会变的很小
        attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(contentLabelFontSize), range: NSMakeRange(0, attributedStr.length))
        
        
        //  添加匹配类型链接颜色
        let matchResults = addLinkColor(RGB(80, green: 125, blue: 175),attributeStr: attributedStr)
        return (attributedStr, matchResults)
    }
    //  根据指定富文本闭包相应类型，进行颜色添加
    private func addLinkColor(color: UIColor, attributeStr: NSMutableAttributedString) -> [CZMatchResult] {
        
        var matchResults: [CZMatchResult] = [CZMatchResult]()
        
        //  匹配@，不是字符
        (attributeStr.string as NSString).enumerateStringsMatchedByRegex("@[^\\W]+") { (count, result, resultRange, _) -> Void in
            print(result.memory!)
             attributeStr.addAttribute(NSForegroundColorAttributeName, value: color, range: resultRange.memory)
            //  添加匹配结果
            matchResults.append(CZMatchResult(string: result.memory! as String, range: resultRange.memory))
        }
        //  匹配http链接 不是空格不是汉字
        (attributeStr.string as NSString).enumerateStringsMatchedByRegex("http://[^\\s^\\u4e00-\\u9fa5^【]+") { (count, result, resultRange, _) -> Void in
            print(result.memory!)
            attributeStr.addAttribute(NSForegroundColorAttributeName, value: color, range: resultRange.memory)
            //  添加匹配结果
            matchResults.append(CZMatchResult(string: result.memory! as String, range: resultRange.memory))
        }
        //  匹配话题
        (attributeStr.string as NSString).enumerateStringsMatchedByRegex("#[^#]+#") { (count, result, resultRange, _) -> Void in
            print(result.memory!)
            attributeStr.addAttribute(NSForegroundColorAttributeName, value: color, range: resultRange.memory)
            //  添加匹配结果
            matchResults.append(CZMatchResult(string: result.memory! as String, range: resultRange.memory))
        }
        
        return matchResults
    }
    
    private func handleMBrankImage(mbrank: Int) {
        if mbrank > 0 && mbrank < 7 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }
    private func handleVerifiedLevelImage(verifiedLevel: Int) {
        //  认证等级 -1 没有认证 ，1 认证用户，2，3，5 企业认证 ， 220 达人
        switch verifiedLevel {
        case 1:
            verifiedLevelImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedLevelImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedLevelImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedLevelImage = nil
        }
    }
    private func handleRetWeetContent() {
        guard let retweetStr = status?.retweeted_status?.text else {
            return
        }
        guard let userName = status?.retweeted_status?.user?.screen_name else {
            return
        }
        
        retweetContent = "@\(userName):\(retweetStr)"
        //  创建转发微博富文本对象
        let result = handleStatusToAttributeString(retweetContent)
        retweetAttributeStr = result.attr
        retweetMatchResults = result.matchResults
        
    }
    private func handleSourceContent() {
        if let source = status?.source {
            //  找到\>的范围
            let startRange = source.rangeOfString("\">")
            //  找到</的范围
            let endRange = source.rangeOfString("</")
            //  获取截取范围的数据
            if let startRange = startRange, endRange = endRange {
                sourceContent = "来自 " + source.substringWithRange(startRange.endIndex..<endRange.startIndex)
            }
            
        }
        
    }

 
}
